package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Transactional
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {
    //final 确保该字段只能被赋值一次，增强代码的安全性
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;


    public AuditServiceImpl(AuditMapper auditMapper, UserMapper userMapper) {
        this.auditMapper = auditMapper;
        this.userMapper = userMapper;
    }

    @Override
    public void insertAudit(Application application) {
        log.debug("为申请单生成对应的审批单:{}", application);
        //1.获取申请中的审批人id集合
        List<Long> auditUserIdList = application.getAuditUserIdList();//[106,103]
        //2.遍历得到每个id,有几个id就生成几条审批单
        for (int i = 0; i < auditUserIdList.size(); i++) {
            //3.创建一个空的审批单对象入库时使用
            Audit audit = new Audit();
            audit.setApplicationId(application.getId());//批哪个申请单 申请单id
            audit.setAuditUserId(auditUserIdList.get(i));//谁来批 审批人id
            audit.setAuditSort(i);//审批次序 0 1 ...
            if(i == 0){//0号审批人，状态为待我审核
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            }else{//其他审批人，状态为待他人审核
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            audit.setCreateTime(new Date());
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        log.debug("根据申请单id查对应审批单业务:{}",id);
        List<AuditVO> list = auditMapper.selectAuditByApplicationId(id);
        return list;
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单业务:{}",auditQuery);
        List<AuditVO> list = auditMapper.selectAudit(auditQuery);
        //遍历得到每个审批VO,为其补全审批人数据
        for(int i = 0; i < list.size(); i++){
            AuditVO auditVO = list.get(i);
            assignAuditUserList(auditVO);
        }
        return list;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("审批申请单业务:{}",auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam,audit);
        audit.setUpdateTime(new Date());
        /* 1. 先更新当前的这条审批单 */
        auditMapper.update(audit);
        //准备当前审批单批的这个申请单对象
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        /* 2. 判断当前操作是通过还是驳回  */
        if(audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){//通过
            /* 3. 继续查其它审批单 */
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            /* 4. 查批此申请单的所有审批单中,还未审批的审批单总数 */
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if(count > 0){//还有未审批的审批单
                /* 5. 查到后面那条审批单 20->10 */
                auditQuery.setAuditSort(audit.getAuditSort() + 1);
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if(auditVOList != null && auditVOList.size() > 0){
                    AuditVO auditVO = auditVOList.get(0);
                    //准备第二个审批单对象,用于更新数据库
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    audit2.setUpdateTime(new Date());
                    auditMapper.update(audit2);
                }
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else{//没有未审批的审批单了,刚刚那条是最后一条审批单
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        }else{//驳回
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if(auditVOList != null && auditVOList.size() > 0){
                for(int i = 0; i < auditVOList.size(); i++){
                    AuditVO auditVO = auditVOList.get(i);
                    if(auditVO.getAuditStatus().equals(AuditStatusEnum.PENDING.getCode())){
                        //删除未审批的审批单,也就是"待他人审核"状态下的审批单
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO) {
        List<String> auditUsernameList = new ArrayList<>();//创建一个用来装审批人姓名的空集合
        List<Long> auditUserIdList = new ArrayList<>();//创建一个用来装审批人id的空集合
        //根据审批单VO中的申请单id,查询当前审批单对应的申请单下的所有审批单数据
        List<AuditVO> auditVOList =
                auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //遍历每一个审批单,获取每个审批单中的审批人id与姓名
        for(int i = 0;i <auditVOList.size();i++){
            Long userId = auditVOList.get(i).getAuditUserId();//获取当前遍历到的审批单的审批人id
            auditUserIdList.add(userId);//将当前的审批人id装到上面的id空集合中
            UserVO user = userMapper.selectById(userId);//根据用户id查出用户VO
            auditUsernameList.add(user.getUsername());//将当前的审批人姓名装到上面的name空集合中
        }
        StringJoiner stringJoiner = new StringJoiner(",");//准备拼接工具
        for (String username : auditUsernameList){//遍历审批人姓名集合并进行拼接
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);//将审批人id数据赋值给审批单VO
        auditVO.setAuditUsernameList(stringJoiner.toString());//将审批人姓名字符串赋值给审批单VO
    }
}
